<!--
	作者：lsd
	时间：2020-2-18
	描述：对账看板
-->

<template>
	<div class="m-view-accountBoardReport m-window">
		<el-tabs
			tab-position="left"
			style="height: 100%;"
			v-model="activeName"
			v-if="showOtherPage==1"
			@tab-click="tabClick"
		>
			<el-tab-pane name="1" label="实物对账" v-loading="loading">
				<!-- 搜索头 -->
				<div class="m-condition">
					<el-form label-width="100px" :inline-message="true" label-position="left">
						<el-row :gutter="10">
							<el-col :span="8">
								<el-form-item label="对账期间" class="rightItem">
									<el-date-picker
										v-model="formSearch.createSt"
										placeholder="开始日期"
										value-format="yyyy-MM-dd"
										:clearable="true"
										:picker-options="pickerOptions"
									></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-date-picker
									v-model="formSearch.createEt"
									:clearable="true"
									placeholder="结束日期"
									value-format="yyyy-MM-dd"
									:picker-options="pickerOptions"
								></el-date-picker>
							</el-col>
							<el-col :span="2">
								<el-button @click="search()" type="primary">查询</el-button>
							</el-col>
							<el-col :span="2">
								<el-button @click="showAllState = false" type="primary" v-show="showAllState">展开</el-button>
							</el-col>
							<el-col :span="2">
								<el-button @click="showAllState = true" type="primary" v-show="!showAllState">收起</el-button>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<!-- 饼图 -->
				<div v-for="(e, index) in list" :key="index">
					<!-- 控制行 -->
					<el-row :gutter="17" style="margin-bottom: 20px" v-if="index %4 == 0 || index == 0">
						<!-- 控制列，一行多四个，不足四个就就显示剩下的 后面的v-show控制展开收起-->
						<el-col
							:span="6"
							style="height: 190px;"
							v-for="(item, id) in getForLength(index)"
							:key="id"
							v-show="showAll(index+id, list[index+id])"
						>
							<span class="m-title">{{list[index+id].companyName, }}</span>
							<chart
								v-if="activeName=='1'"
								:options="gooChartOptionList[index+id]"
								:id="`gooChart${list[index+id].companyCode}`"
								:height="'190px'"
								:width="'100%'"
								@chartClick="chartClick"
							></chart>
						</el-col>
					</el-row>
				</div>
				<span class="suppelier-num">{{spanVal}}</span>
				<!--列表-->
				<div class="table-wrap">
					<div class="m-agTable m-bottom">
						<agGridComponents
							ref="gooGrid"
							:isColFit="true"
							:getGridOptions="reportGridOptions"
							:getColumnDefs="supplierColumnDefs"
						></agGridComponents>
					</div>
					<!-- 分页组件 -->
					<div class="m-page">
						<el-pagination
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
							@prev-click="handlePrevClick"
							@next-click="handleNextClick"
							:current-page="pageInfo.current"
							:page-sizes="[30,50,100,150,200]"
							:page-size="pageInfo.size"
							layout="total, sizes, prev, pager, next, jumper"
							:total="pageInfo.total"
						></el-pagination>
					</div>
				</div>
			</el-tab-pane>
			<el-tab-pane name="2" label="会计对账" v-loading="loading">
				<!-- 搜索头 -->
				<div class="m-condition">
					<el-form label-width="100px" :inline-message="true" label-position="left">
						<el-row :gutter="10">
							<el-col :span="8">
								<el-form-item label="对账期间" class="rightItem">
									<el-date-picker
										v-model="formSearch.createSt"
										placeholder="开始日期"
										value-format="yyyy-MM-dd"
										:clearable="true"
									></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-date-picker
									v-model="formSearch.createEt"
									:clearable="true"
									placeholder="结束日期"
									value-format="yyyy-MM-dd"
								></el-date-picker>
							</el-col>
							<el-col :span="2">
								<el-button @click="search()" type="primary">查询</el-button>
							</el-col>
							<el-col :span="2">
								<el-button @click="showAllState = false" type="primary" v-show="showAllState">展开</el-button>
							</el-col>
							<el-col :span="2">
								<el-button @click="showAllState = true" type="primary" v-show="!showAllState">收起</el-button>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<!-- 饼图 -->
				<div v-for="(e, index) in list" :key="index">
					<!-- 控制行 -->
					<el-row :gutter="17" style="margin-bottom: 20px" v-if="index %4 == 0 || index == 0">
						<!-- 控制列，一行多四个，不足四个就就显示剩下的 后面的v-show控制展开收起 -->
						<el-col
							:span="6"
							style="height: 190px;"
							v-for="(item, id) in getForLength(index)"
							:key="id"
							v-show="showAll(index+id, item)"
						>
							<span class="m-title">{{list[index+id].companyName}}</span>
							<chart
								v-if="activeName=='2'"
								:options="accChartOptionList[index+id]"
								:id="`accChart${list[index+id].companyCode}`"
								:height="'190px'"
								:width="'100%'"
								@chartClick="chartClick"
							></chart>
						</el-col>
					</el-row>
				</div>
				<span class="suppelier-num">{{spanVal}}</span>
				<!--列表-->
				<div class="table-wrap">
					<div class="m-agTable m-bottom">
						<agGridComponents
							ref="accountGrid"
							:isColFit="true"
							:getGridOptions="reportGridOptions"
							:getColumnDefs="supplierColumnDefs"
						></agGridComponents>
					</div>
					<!-- 分页组件 -->
					<div class="m-page">
						<el-pagination
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"
							@prev-click="handlePrevClick"
							@next-click="handleNextClick"
							:current-page="pageInfo.current"
							:page-sizes="[30,50,100,150,200]"
							:page-size="pageInfo.size"
							layout="total, sizes, prev, pager, next, jumper"
							:total="pageInfo.total"
						></el-pagination>
					</div>
				</div>
			</el-tab-pane>
		</el-tabs>
		<!-- 会计明细报表 -->
		<div class="m-window" v-if="showOtherPage==2">
			<accountMxReport :setClickValue="linkValue"></accountMxReport>
		</div>
		<!-- 实物明细报表 -->
		<div class="m-window" v-if="showOtherPage==3">
			<goodsAccountReport :setClickValue="linkValue"></goodsAccountReport>
		</div>
	</div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import Chart from "@/components/eCharts";
import agGridComponents from "@/components/agGridComponents.js";
import goodsAccountReport from "@/views/purchaseReport/goodsAccountReport";
import accountMxReport from "@/views/purchaseReport/accountMxReport";
import serviceTime from "@/public/serverTime.js";
import Msg from "@/public/message.js";
import waterfall from 'async-es/waterfall';
import Vue from 'vue';

const btnLink = Vue.extend({
	template: `<span v-if="!params.node.data.flag">
      <el-button type="text" @click="details" class="rendererClass" size="mini">{{params.value}}</el-button>
    </span>`,
	methods: {
		details () {
			this.params.context.componentParent.linkValue.no = this.params.value;
			if (this.params.context.componentParent.activeName == '1') {
				this.params.context.componentParent.showOtherPage = 3;//实物
			} else {
				this.params.context.componentParent.showOtherPage = 2;//会计
			}

		},
	}
});

export default {
	components: {
		Chart, agGridComponents, goodsAccountReport, accountMxReport
	},
	data () {
		return {
			loading: false,
			showAllState: false,//true 展开，false收起
			activeName: '1',//1实物，2会计（注意是字符串1）
			showOtherPage: 1,//1显示本页，2显示会计明细报表，3显示实物明细报表
			gooChartOptionList: [],//实物对账图表配置列表
			accChartOptionList: [],//会计对账图表配置列表
			supplierColumnDefs: [],//供应商的表格配置
			gooBillsColumnDefs: [],//对账单的表格配置
			list: [],//饼图数据
			tableData: [],//表格数据
			chartData: {},//饼图点击数据
			spanVal: "已对应供应商: 0个",//table上面那句话
			linkValue: {
				no: ''
			},
			formSearch: {
				createSt: '',
				createEt: '',
			},
			// 分页信息
			pageInfo: {
				current: 1,
				size: 30,
				total: 0
			},
			//日期设置
			pickerOptions: {
				disabledDate (time) {
					return time.getTime() > Date.now();
				},
			},
		}
	},
	beforeMount () {
		//表格配置
		this.reportGridOptions = {
			context: { componentParent: this },
			enableColResize: true,
			localeText: localeText,
			//pinnedBottomRowData: this.createData(1, 'Bottom'),
			suppressRowClickSelection: true,//单元格选中,false为选中整行
		};
		//供应商表格列配置
		this.supplierColumnDefs = [
			{ headerName: "公司", field: "companyCode", width: 70 },
			{ headerName: "公司名称", field: "companyName", width: 120 },
			{ headerName: "供应商", field: "supplierCode", width: 100 },
			{ headerName: "供应商名称", field: "supplierName", width: 120 },
			{ headerName: "对账单", field: "quantity", width: 80 },
			{ headerName: "对账金额", field: "amount", width: 100 },
		];
		// 实物对账单据表格列配置
		this.gooBillsColumnDefs = [
			{ headerName: "公司", field: "companyCode", width: 70 },
			{ headerName: "公司名称", field: "companyName", width: 120 },
			{ headerName: "供应商", field: "supplierCode", width: 100 },
			{ headerName: "供应商名称", field: "supplierName", width: 120 },
			{ headerName: "对账单号", field: "gooAccNo", width: 100, cellRendererFramework: btnLink },
			{
				headerName: "单据日期",
				field: "createDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "对账金额", field: "amount", width: 100 },
			{
				headerName: "状态",
				field: "billState",
				width: 70,
				cellRenderer: function (params) {
					if (params.value == "1")
						return '<span class="ag-icon">已保存</span>';
					else if (params.value == "2")
						return '<span class="ag-icon">已提交</span>';
					else if (params.value == "3")
						return '<span class="ag-icon">已确认</span>';
					else if (params.value == "4")
						return '<span class="ag-icon">已审核</span>';
				}
			},
			{ headerName: "应付人员", field: "confirmer", width: 100, type: ['textColumn'] },
		];
		// 会计对账单据表格列配置
		this.accBillsColumnDefs = [
			{ headerName: "公司", field: "companyCode", width: 70 },
			{ headerName: "公司名称", field: "companyName", width: 120 },
			{ headerName: "供应商", field: "supplierCode", width: 100 },
			{ headerName: "供应商名称", field: "supplierName", width: 120 },
			{ headerName: "对账单号", field: "accountNo", width: 100, cellRendererFramework: btnLink },
			{
				headerName: "单据日期",
				field: "createDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value)
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "对账金额", field: "amount", width: 100 },
			{
				headerName: "状态",
				field: "billState",
				width: 70,
				cellRenderer: function (params) {
					if (params.value == "1")
						return '<span class="ag-icon">已保存</span>';
					else if (params.value == "2")
						return '<span class="ag-icon">已提交</span>';
					else if (params.value == "3")
						return '<span class="ag-icon">已确认</span>';
					else if (params.value == "4")
						return '<span class="ag-icon">已审核</span>';
				}
			},
			{ headerName: "应付人员", field: "confirmer", width: 100, type: ['textColumn'] },
		]
	},
	mounted () {
		this.search();
		//this.initDate();
		//this.initDataFunc();
	},
	methods: {
		//查询
		search () {
			let list = new Promise((resolve, reject) => {

				//输入验证
				if (this.formSearch.createSt > this.formSearch.createEt) {
					this.$alert("结束日期不能比开始时间小！", { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					return
				}

				this.loading = true;

				let param = {
					...this.formSearch
				}

				if (this.activeName == '1') { //实物
					_Api
						.getGooChartData({ data: param })
						.then(({ data }) => {
							this.loading = false;
							if (data.code == 1) {
								this.list = data.rows;
								resolve(data.rows)
							} else {
								reject(data.info)
							}
						})
						.catch(err => {
							this.loading = false;
							reject(err.data.info)
						});
				}
				else if (this.activeName == '2') {//会计
					_Api
						.getAccChartData({ data: param })
						.then(({ data }) => {
							this.loading = false;
							if (data.code == 1) {
								this.list = data.rows;
								resolve(data.rows)
							} else {
								reject(data.info)
							}
						})
						.catch(err => {
							this.loading = false;
							reject(err.data.info)
						});
				}
			})
			//要这个才行，vchart这东西,咦~
			Promise.all([list]).then((result) => {
				this.loading = false
				if (result.length > 0) {
					this.setChartData(result[0]);
				}
			}).catch((error) => {
				//清空
				this.clearParame();
				this.$alert(error, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
			})
		},
		//饼图点击
		chartClick (val) {
			//初始化参数
			let { flag, companyCode, isRecony, title, name, value, billState } = val.data;
			let { createSt, createEt } = this.formSearch;
			let { current, size } = this.pageInfo;
			let param = { flag, companyCode, isRecony, billState, current, size, createSt, createEt };
			this.chartData = { flag, companyCode, isRecony, billState, createSt, createEt };

			if (flag == 1) {//里圈的饼图，供应商
				this.spanVal = `${title}的供应商: ${value}个`;
				//设置表格设置
				this.$refs.accountGrid.gridOptions.api.setColumnDefs(this.supplierColumnDefs);
				this.$refs.gooGrid.gridOptions.api.setColumnDefs(this.supplierColumnDefs);
			}
			else if (flag == 2) {//外圈的饼图，表据
				this.spanVal = `${name}的单据: ${value}个`;
				if (this.activeName == '1') {//为实物对账
					this.$refs.accountGrid.gridOptions.api.setColumnDefs(this.gooBillsColumnDefs);
					this.$refs.gooGrid.gridOptions.api.setColumnDefs(this.gooBillsColumnDefs);
				} else if (this.activeName == '2') {//为会计对账
					this.$refs.accountGrid.gridOptions.api.setColumnDefs(this.accBillsColumnDefs);
					this.$refs.gooGrid.gridOptions.api.setColumnDefs(this.accBillsColumnDefs);
				}
			}

			//调用接口
			if (this.activeName == '1') {//实物
				this.getGoodBillList(param);
			} else if (this.activeName == '2') {//会计
				this.getAccBillList(param);
			}

		},
		//获取实物已/未对账的单据
		getGoodBillList (param) {
			this.loading = true;
			_Api
				.getGooBillData({ data: param })
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.pageInfo.total = res.data.total;
						this.$refs.gooGrid.gridOptions.api.setRowData(res.data.rows);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},
		//获取会计已/未对账的单据
		getAccBillList (param) {
			this.loading = true;
			_Api
				.getAccBillData({ data: param })
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.pageInfo.total = res.data.total;
						this.$refs.accountGrid.gridOptions.api.setRowData(res.data.rows);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},
		//获取公司列表
		getCompanyList () {

		},
		//重置参数
		clearParame () {
			this.pageInfo.current = 1;
			this.pageInfo.size = 30;
			this.pageInfo.total = 0;
			this.list = [];
			this.tableData = [];
			this.$refs.accountGrid.gridOptions.api.setRowData([]);
			this.$refs.gooGrid.gridOptions.api.setRowData([]);
			this.gooChartOptionList = [];
			this.accChartOptionList = [];
		},
		// 初始化饼图
		setChartData (list) {
			this.accChartOptionList = [];
			this.gooChartOptionList = [];
			for (let i = 0; i < list.length; i++) {
				const { confirmAmount, newAmount, reconciledAmount, submitAmount, unReconciledAmount, companyCode } = list[i];
				let options = {
					tooltip: {
						trigger: 'item',
						formatter: "{a} <br/>{b}: {c} ({d})%"
					},
					series: [
						{
							name: `${this.activeName == 1 ? '实物' : '会计'}对账单统计(份)`,
							type: 'pie',
							selectedMode: 'single',
							radius: [0, '30%'],
							label: {
								normal: {
									position: 'inner'
								}
							},
							labelLine: {
								normal: {
									show: false
								}
							},
							data: [
								{
									value: reconciledAmount,
									name: `已对账:${reconciledAmount}`,
									title: '已对账',
									//hoverAnimation: false,
									isRecony: true,
									companyCode: companyCode,
									flag: 1
								}, {
									value: unReconciledAmount,
									name: `未对账:${unReconciledAmount}`,
									title: '未对账',
									//	hoverAnimation: false,
									isRecony: false,
									companyCode: companyCode,
									flag: 1								}
							]
						}, {
							name: `${this.activeName == 1 ? '实物' : '会计'}对账单统计(份)`,
							type: 'pie',
							radius: ['45%', '60%'],

							data: [
								{ value: newAmount, name: '已保存', flag: 2, billState: 1, companyCode: companyCode, },
								{ value: confirmAmount, name: '已确认', flag: 2, billState: 3, companyCode: companyCode, },
								{ value: submitAmount, name: '已提交', flag: 2, billState: 2, companyCode: companyCode, }
							]
						},
					]
				};
				if (this.activeName == '1') {//为实物
					this.gooChartOptionList.push(options);
				} else if (this.activeName == '2') {//为账号
					this.accChartOptionList.push(options);
				}

			}
		},
		//返回for循环的一个长度
		getForLength (index) {
			let val = this.list.length - index;
			if (val < 4 || val == 4) {
				return val;
			} else if (val > 4) {
				return 4;
			}
		},
		//展开，收起
		showAll (index, item) {
			if (item.companyCode == "")
				return false
			if (this.showAllState) {
				return index <= 3
			} else {
				return true
			}

		},
		//tab点击
		tabClick (val) {
			//重置参数
			this.clearParame();
			if (val.name == '1') {//为实物对账
				this.$refs.accountGrid.gridOptions.api.setColumnDefs(this.gooBillsColumnDefs);
				this.$refs.gooGrid.gridOptions.api.setColumnDefs(this.gooBillsColumnDefs);
			} else if (val.name == '2') {//为会计对账
				this.$refs.accountGrid.gridOptions.api.setColumnDefs(this.accBillsColumnDefs);
				this.$refs.gooGrid.gridOptions.api.setColumnDefs(this.accBillsColumnDefs);
			}
			//
			this.search();
		},
		//初始化时间
		initDate (callback) {
			// 日期范围默认30天内
			serviceTime.getServiceTime().then((serviceTime) => {
				this.formSearch.createSt = new Date(serviceTime.getTime() - 3600 * 1000 * 24 * 30).Format('yyyy-MM-dd')
				this.formSearch.createEt = serviceTime.Format("yyyy-MM-dd")
				callback();
			}).catch(err => {
				Msg.showErrorMsg(err)
			})
		},
		//初始化方法
		initDataFunc () {
			waterfall([
				(callback) => {
					this.initDate(callback)
				},
				(callback) => {
					this.search(callback)
				},
				(err, result) => {
					console.log(err)
				}
			])
		},
		// 每页条数改变回调
		handleSizeChange (size) {
			this.pageInfo.size = size;
			this.pageInfo.current = 1;
			let param = {
				...this.chartData,
				current: this.pageInfo.current,
				size
			}
			//调用接口
			if (this.activeName == '1') {//实物
				this.getGoodBillList(param);
			} else if (this.activeName == '2') {//会计
				this.getAccBillList(param);
			}
		},
		// 页码改变回调
		handleCurrentChange (current) {
			this.pageInfo.current = current;
			let param = {
				...this.chartData,
				current,
				size: this.pageInfo.size
			}
			//调用接口
			if (this.activeName == '1') {//实物
				this.getGoodBillList(param);
			} else if (this.activeName == '2') {//会计
				this.getAccBillList(param);
			}
		},
		// 点击上一页回调
		handlePrevClick (current) {
			this.pageInfo.current = current
		},
		// 点击下一页回调
		handleNextClick (current) {
			this.pageInfo.current = current
		},
	},
}
</script>

<style lang="less">
.m-view-accountBoardReport {
	.el-tabs__item {
		background-color: unset;
	}
	.el-tabs__content {
		position: relative;
		top: unset;
		bottom: unset;
		left: unset;
		right: unset;
		height: 100%;
		overflow-x: hidden;
		overflow-y: auto;
	}
	.suppelier-num {
		line-height: 40px;
	}
	.table-wrap {
		position: relative;
		width: 100%;
		height: 235px;
		.m-agTable {
			height: 200px;
		}
	}
}
</style>
